<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽效果</title>
    <style>
        .wai{
            width: 400px;
            height: 400px;
            border:solid 1px #aaa;
            display:flex;
            justify-content:center;
            align-items:center;
            margin: 50px auto;
            position:relative;
        }
        .nei{
            width: 100px;
            height: 100px;
            position:absolute;
            left: 0;
            top: 0;
            border:solid 1px #123;
        }
    </style>
</head>
<body>
    <div id="root"></div>

    <script src="../js/react.development.js"></script>
    <script src="../js/react-dom.development.js"></script>
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">
        class App extends React.Component {
            render(){
                return <div className="wai"
                    onMouseMove={this.mousemove}      
                >
                        <div className="nei" ref={el => this.nei = el} 
                            onMouseDown={this.mousedown}  onMouseUp ={this.mouseup}
                        >
                        </div>
                    </div>
            }
            //鼠标按下的事件
            mousedown = (e) => {
                //设置状态
                this.isDown = true;
                this.x = e.pageX;
                this.l = this.nei.offsetLeft;

                this.y = e.pageY;
                this.t = this.nei.offsetTop;
            }

            //鼠标移动事件
            mousemove = e => {
                //判断 如果鼠标没有按下, 则不移动
                if(!this.isDown) return;
                let _x = e.pageX;
                let _y = e.pageY;

                //计算最终的left 的值
                let newLeft = _x - this.x + this.l;
                let newTop = _y -this.y + this.t;
                //设置
                this.nei.style.left = newLeft + 'px';
                this.nei.style.top = newTop + 'px';
            }

            //鼠标抬起事件
            mouseup = ()=>{
                this.isDown = false;
            }
        }

        ReactDOM.render(<App />, document.querySelector('#root'));

    </script>
</body>
</html>